# -*- coding:utf-8 -*-
import time
import requests
import json

import datetime
from jd_logger import logger
from config import global_config


class Timer(object):
    def __init__(self, sleep_interval=0.5):
        # '2018-09-28 22:45:50.000'
        self.buy_time = datetime.datetime.strptime(global_config.getRaw('config','buy_time'), "%Y-%m-%d %H:%M:%S.%f")
        self.buy_time_ms = int(time.mktime(self.buy_time.timetuple()) * 1000.0 + self.buy_time.microsecond / 1000)
        self.sleep_interval = sleep_interval

        self.diff_time = self.local_jd_time_diff()

    def jd_time(self):
        """
        从京东服务器获取时间毫秒
        :return:
        """
        url = 'https://a.jd.com//ajax/queryServerData.html'
        ret = requests.get(url).text
        js = json.loads(ret)
        return int(js["serverTime"])
    
    def jd_time_v2(self):
        """
        从京东服务器获取时间毫秒V2
        :return:
        """
        r1 = requests.get(url='https://api.m.jd.com/client.action?functionId=queryMaterialProducts&client=wh5',
                          headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.190.400 QQBrowser/11.5.5240.400'})

        x = eval(r1.text)
        timeNum = int(x['currentTime2'])
        
        timeStamp = int(timeNum)
        # ret_datetime = datetime.datetime.utcfromtimestamp(timeStamp).strftime("%Y-%m-%d %H:%M:%S.%f")
        logger.info('jd_time:{}'.format(x['currentTime']))
        return timeStamp

    def local_time(self):
        """
        获取本地毫秒时间
        :return:
        """
        lc_time = int(round(time.time() * 1000))
        logger.info('lc_time:{}'.format(time.asctime(time.localtime(time.time()))))
        return lc_time
    
    # def local_time_v2(self):
    #     """
    #     获取本地毫秒时间
    #     :return:
    #     """
    #     return int(datetime.datetime.now().microsecond() / 1000)

    def local_jd_time_diff(self):
        """
        计算本地与京东服务器时间差
        :return:
        """
        ttl = 22
        return self.local_time() - self.jd_time_v2() - ttl / 2

    def start(self):
        logger.info('正在等待到达设定时间:{}，检测本地时间与京东服务器时间误差为【{}】毫秒'.format(self.buy_time, self.diff_time))
        while True:
            # 本地时间减去与京东的时间差，能够将时间误差提升到0.1秒附近
            # 具体精度依赖获取京东服务器时间的网络时间损耗
            if self.local_time() - self.diff_time >= self.buy_time_ms:
                logger.info('时间到达，开始执行……')
                break
            else:
                time.sleep(self.sleep_interval)
